// 使用go第三方库gin1.6.3实现Fabric1.4.8应用中的Restful API
package controller

import (
	"github.com/artec/web/service"
	"github.com/gin-gonic/gin"
	"net/http"
)

// http://localhost:9000
func Index(ctx *gin.Context) {
	ctx.String(http.StatusOK, "Welcome!")
}

// http://localhost:9000/query/A
func Query(ctx *gin.Context) {
	name := ctx.Param("name") //从URL中的name属性中获取账户名
	msg, err := service.Query(name)
	if err != nil {
		msg = "没有查询到" + name + "的账户信息"
	}

	// 构造map[string]interface，并序列化为JSON格式，存入responseBody
	//响应给客户端的同时，将Content-Type置为"application/json"
	ctx.JSON(http.StatusOK, gin.H{
		"UserName": name,
		"Message":  msg,
	})
}

// http://localhost:9000/transfer?name1=A&name2=B&count=10
func Transfer(ctx *gin.Context) {
	from := ctx.Query("name1") //查询URL中?后面的键值对中的"name1"参数
	to := ctx.Query("name2")
	count := ctx.Query("count")
	transactionID, err := service.Transfer(from, to, count)
	var msg string
	if err != nil {
		msg = err.Error()
	} else {
		msg = transactionID
	}
	//转账的过程中不管是否成功，都返回OK???
	ctx.JSON(http.StatusOK, gin.H{
		"Trom":    from,
		"To":      to,
		"Count":   count,
		"Message": msg,
	})
}

// http://localhost:9000/delete/A
func Delete(ctx *gin.Context) {
	var msg string
	name := ctx.Param("name")
	count, err := service.Query(name)
	if err != nil {
		msg = "没有查询到" + name + "的账户信息"
	} else {
		transactionID, err := service.Delete(name)
		if err != nil {
			msg = err.Error()
		} else {
			msg = transactionID
		}
	}

	ctx.JSON(http.StatusOK, gin.H{
		"UserName": name,
		"Count":    count,
		"Message":  msg,
	})
}

// http://localhost:9000/register?name=C&count=300
func Register(ctx *gin.Context) {
	var msg string
	name := ctx.Query("name")
	count := ctx.Query("count")
	transactionID, err := service.Register(name, count)
	if err != nil {
		msg = err.Error()
	} else {
		msg = transactionID
	}

	ctx.JSON(http.StatusOK, gin.H{
		"UserName": name,
		"Count":    count,
		"Message":  msg,
	})
}
